/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.itjisu.hongbao.core;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import com.itjisu.hongbao.constants.ConfigEntry;
import com.itjisu.hongbao.constants.GlobalConfig;
import com.itjisu.hongbao.model.RedBagEntity;
import com.itjisu.hongbao.util.MLog;
import com.itjisu.hongbao.util.ManageKeyguard;
import com.itjisu.hongbao.util.ManageScreen;
import com.itjisu.hongbao.util.Util;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

/**
 * This class demonstrates how an accessibility service can query window content
 * to improve the feedback given to the user.
 */
@SuppressWarnings("deprecation")
public class QiangHongBaoService extends AccessibilityService {

//    static {
//        System.loadLibrary("hb");
//    }

//	public native static int home();

//	public native static int touch(int x, int y);

    private Handler handler = new Handler();

    private static String pageClassName;

    private static int obj = -1;//0:微信红包  1：qq红包

    public static boolean ISRUNNING=false;//正在抢红包；
    //	private static int state = 0;
    public static boolean RUN = false;

    RedBagEntity entity = new RedBagEntity();

    private Context appContext;

    private static QQAction qqAction = null;
    private static WeChatAction weChatAction = null;

    /**
     * {@inheritDoc}
     */
    @Override
    public void onServiceConnected() {
        appContext = getApplicationContext();
        RUN = true;
//        Toast.makeText(this.getApplicationContext(), "onServiceConnected...", Toast.LENGTH_LONG).show();
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
                | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
        info.notificationTimeout = 100;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        setServiceInfo(info);

        obj = -1;

        ConfigEntry.serviceIsON = true;
        qqAction = new QQAction(entity, this);
        weChatAction = new WeChatAction(entity, this);
        Util.httpPing(QiangHongBaoService.this, Util.SERVER_URL_START + Util.getCommonParam(QiangHongBaoService.this));
        MobclickAgent.onEvent(this, "startservice");
        if (SplashActivity.splashOK) {
            Toast.makeText(this.getApplicationContext(), "抢红包已开启...", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(this, QiangHongBaoActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }


    private static boolean resetState = true;

    private void resetState() {
        final long period = ConfigEntry.getDelayCanTimeVip() + ConfigEntry.getDelayReplyCanTimeVip() + 15000;
        new Thread(new Runnable() {
            @Override
            public void run() {
                long cur = System.currentTimeMillis();
                while (resetState) {
                    SystemClock.sleep(1000);
                    if (System.currentTimeMillis() - cur > period) {
                        obj = -1;
                        resetState = false;
//                        Util.httpPing(appContext, Util.ACTION_URL + Util.getCommonParam(appContext) + "&clkid=" + Util.ACTION_ID_RESET_STATE + "&status=" +
//                                entity.getStatus() + "&page=" + pageClassName);
                        entity.setReason("暂时未抢到哦~");
                        gotoMyActivity("2.reset State");
                        ManageScreen.lightOff(appContext);
                        ManageKeyguard.reenableKeyguard();
                    }
                }
                // Log.d("resetState canceled:"+(System.currentTimeMillis() - cur - period));
            }
        }).start();
    }

    private void lightScreenOn() {
        try {
            // Log.d("mKeyguardLockPrevious inKeyguardRestrictedInputMode:" + ManageKeyguard.inKeyguardRestrictedInputMode(appContext) );
            ManageScreen.lightOn(appContext);
            if (ManageKeyguard.inKeyguardRestrictedInputMode(appContext) && ConfigEntry.getLockedCanVip()) {
                ManageKeyguard.disableKeyguard(this);
            }
        } catch (Exception e) {
            if (GlobalConfig.isDebug) {
                e.printStackTrace();
                Log.d(GlobalConfig.TAG, "Exception:" + e.getMessage());
            }
        }
    }

    private void closeScreen() {

        ManageKeyguard.reenableKeyguard();
        ManageScreen.lightOff(this.getApplicationContext());

    }

    private void clickNotif(final int which, AccessibilityEvent event, String aString, int index) {
//        entity = new RedBagEntity();
        if (ManageKeyguard.inKeyguardRestrictedInputMode(appContext) && !ConfigEntry.getLockedCanVip()) {
            return;
        }
        lightScreenOn();

        String temp = aString.substring(0, index - 1).trim();
        String nickName = temp;
        try {
            if (temp.endsWith(":")) {
                nickName = temp.substring(0, temp.length() - 1);
            }
        } catch (Exception e) {
        }
        entity.setSend_nickname(nickName);
        // Log.d("TYPE_WINDOW_STATE_CHANGEDClass:nickName:" + nickName);

        final Notification parcelable = (Notification) event.getParcelableData();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    parcelable.contentIntent.send();
//                    playSound();

                    resetState = true;
                    resetState();
                    if (which == 0) {
                        obj = 0;
                    } else {
                        obj = 1;
                    }
                    //  Log.d("TYPE_WINDOW_STATE_CHANGEDClass:receive notif ");

                } catch (Exception e1) {

                }

            }
        }, ConfigEntry.getDelayCanTimeVip() * 1000);
    }

    private void analyzeNotif(AccessibilityEvent event) {
        List<CharSequence> texts = event.getText();
        for (CharSequence cs : texts) {
            if (cs != null) {
                String aString = cs.toString();
                 MLog.d("analyzeNotif:"+aString);
                int index = aString.indexOf("[微信红包]");
                if (index >= 0 && ConfigEntry.getIsWeiXinOpen()) {
                    clickNotif(0, event, aString, index);
                    entity.setFrom("wechat");
                    break;

                } else {
                    int qqIndex = aString.indexOf("[QQ红包]");
                    // Log.d("TYPE_NOTIFICATION_STATE_CHANGED:" + aString + " " + qqIndex);
                    if (qqIndex >= 0 && ConfigEntry.getIsQQOpen()) {
                        clickNotif(1, event, aString, qqIndex);
                        entity.setFrom("qq");
                        break;
                    }
                }
            }
        }
    }

    private static long lastActive = 0;

    @Override
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void onAccessibilityEvent(AccessibilityEvent event) {
        RUN = true;
        int type = event.getEventType();
        MLog.d("type==wx " + type);
//        MLog.d("type=="+AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            pageClassName = event.getClassName().toString();
        }

//        Log.e("xiaoke", "Get NOTIFI type " + event.getEventType() + "  obj=" + obj);
//        if(type == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && event.getClassName().toString().equals("android.widget.TextView")){
//            AccessibilityNodeInfo nodeInfo = event.getSource();
//            while (nodeInfo != null && nodeInfo.getParent() != null) {// 拿到根节点
//                nodeInfo = nodeInfo.getParent();
//            }
//            MLog.d("MAIN TYPE_WINDOW_CONTENT_CHANGED find = " + nodeInfo.findAccessibilityNodeInfosByText("微信红包").size());
//        }

//        if (System.currentTimeMillis() - lastActive > 3600 * 1000) {//小时级别日志
//
//            lastActive = System.currentTimeMillis();
//            Util.httpPing(appContext, Util.SERVER_URL_PING + Util.getCommonParam(appContext) + "&page=" + pageClassName + "&evetype=" + type +
//                    "&hour=" + new SimpleDateFormat("MM_dd_HH_mm").format(System.currentTimeMillis()));
//        }

        if (!ConfigEntry.getIsWeiXinOpen() && !ConfigEntry.getIsQQOpen()) {
            return;
        }
        if (weChatAction.weChatLate || weChatAction.retToInLauncherUI) {
            MLog.d("pageClassName2 = " + pageClassName);
            if (pageClassName != null && pageClassName.startsWith("com.tencent.mm")) {
                performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            } else {
                gotoMyActivity("4. late for wechat");
            }
            return;
        }

        if (qqAction.qqLate) {
            if (pageClassName != null && pageClassName.startsWith("com.tencent.mobileqq")) {
                performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            } else {
                gotoMyActivity("7.qq late for qq");
            }
            return;
        }

        if (type == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED && obj == -1&&ISRUNNING) {
            analyzeNotif(event);
        }

//        if (GlobalConfig.isDebug) {
//            Log.d(GlobalConfig.TAG,"GlobalConfig Type =" +type + " pageClassName=" + pageClassName);
//        }

        MLog.d("obj==="+obj);
        if (obj == 0 && ConfigEntry.getIsWeiXinOpen()) {
            MLog.d("pageClassName =wx " + pageClassName);
            weChatAction.handleWechat(pageClassName, event);
        } else if (obj == 1 && ConfigEntry.getIsQQOpen()) {
            qqAction.handleQQ(pageClassName, event);
        }
    }

    long ts = System.currentTimeMillis();

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void gotoMyActivity(String cause) {
//        Log.d("gotoMyActivity:"+cause);
//        if (System.currentTimeMillis() - ts > 1000) {//不同手机可能由于延时，会多次调用此处，需控制add日志只发送一条
//            Util.httpPing(this, Util.SERVER_URL_ADD + Util.getCommonParam(this) + "&" + entity.toString());
//            ts = System.currentTimeMillis();
//        }
        obj = -1;
        resetState = false;

//        initVariables();
        qqAction.reset();
        weChatAction.reset();
        MLog.d("Goto Activity money=" + entity.getMoney() + " from=" + entity.getFrom() + " Reason=" + entity.getReason() + " cause=" + cause);
        Intent intent = new Intent(this, QiangHongBaoActivity.class);
        intent.putExtra(QiangHongBaoActivity.MONEY_OF_THIS_TIME, entity.getMoney());
        intent.putExtra(QiangHongBaoActivity.MONEY_FROM, entity.getFrom());
        intent.putExtra(QiangHongBaoActivity.NO_MONEY_REASON, entity.getReason());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        entity.reset();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        obj = -1;
        ConfigEntry.serviceIsON = false;
        return super.onUnbind(intent);
    }

    @Override
    public void onInterrupt() {
        obj = -1;
        ConfigEntry.serviceIsON = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        obj = -1;
        ConfigEntry.serviceIsON = false;
    }
}
